from fastapi import Depends, HTTPException, Request
from fastapi.security import HTTPBearer
from typing import Optional

security = HTTPBearer()  # 默认token前缀Bearer


# 权限装饰器：必须是登录用户
def permission_islogin():
    def decorator(func):
        async def wrapper(request: Request, token: Optional[str] = Depends(security)):
            if token:
                # 1、验证token是否过期
                token_str = token.credentials
                # 2、解析token用户信息
                user = {
                    'username': 'zhangetrs',
                    'id': 1,
                }
                # 3、存入request对象中：用户信息,form表单数据
                request.state.user = user
                request.state.data = await request.form()
                new_request = await func(request)
                return new_request
            else:
                data = {
                    'status': 0,
                    'message': 'token不存在！',
                    'data': 11,
                }
                raise HTTPException(status_code=401, detail=data)

        return wrapper

    return decorator


# 请求传参装饰器：必须是登录用户
def app_request():
    def decorator(func):
        async def wrapper(request: Request):
            # 前端参数存入request对象中：form表单数据,json数据
            request.state.data = await request.form()
            request.state.json = await request.body()
            new_request = await func(request)
            return new_request

        return wrapper

    return decorator
